from Data_Type import *
from MEMORY import *
from Register_File import *
from IF import *
from ID import *
from EX import *
from MEM import *
from WB import *


# 运行实验号
SHIYAN = 1

#内存初始化
RF = register_file(32)      #初始化含有32个32位寄存器的寄存器文件

mem = Memory(16384) # 16MB 16777216   # 1MB  1048576     # 16KB   16384    # 4KB   
mmu = MMU()

text_virtual_address_begin = 0x00400000
text_phy_address_begin = mmu.Linear2Physical(text_virtual_address_begin,mem,0)
data_virtual_address_begin = 0x10010000
data_phy_address_begin = mmu.Linear2Physical(data_virtual_address_begin,mem)
stack_virtual_address_begin = 0x7fffeffc #0x7ffff0fc 
stack_phy_address_begin = mmu.Linear2Physical(stack_virtual_address_begin,mem)
# Real_init()

if SHIYAN == 2:
    ### 加载数据  Fibonacci 30th
    dl = [0x20656854,0x72696874,0x74656974,0x74692068,0x69206d65,0x64253a73]
    for i in range(len(dl)):
        mem.Data32_port_in(dl[i] & 0xFFFFFFFF,data_phy_address_begin + 4*i)
elif SHIYAN == 1:
    ### 加载数据  Fibonacci 10th
    dl = [0x20656854,0x746e6574,0x74692068,0x69206d65,0x64253a73]
    for i in range(len(dl)):
        mem.Data32_port_in(dl[i] & 0xFFFFFFFF,data_phy_address_begin + 4*i)
elif SHIYAN == 0:
    ### 加载数据  冒泡排序
    dl = [0x20,0x04,0x68,0x1111,0x01,0x12,0x0,0x123,0x7]
    for i in range(len(dl)):
        mem.Data32_port_in(dl[i] & 0xFFFFFFFF,data_phy_address_begin + 4*i)


PC = register(text_virtual_address_begin)

SP = RF.files[2]
SP.set(stack_virtual_address_begin)



while True:
    Instr = IF(PC,mem,mmu)
    #print("0x%08x"%PC.value,"0x%08x"%Instr)  输出执行的机器码
    if Instr == 0:
        print("over")
        break
    micro_opt, rs1, rs2, rd, imm = ID(Instr)
    micro_opt, ex2reg_value, ex2mem_value, addr, PC = EX(micro_opt, RF.files[rs1], RF.files[rs2], imm, PC, mem, RF, mmu)
    mem2reg_value, mem = MEM(micro_opt, ex2mem_value, mem, mmu, addr)
    RF = WB(micro_opt, rd, ex2reg_value, mem2reg_value, RF)

###输出text段
print("############text段###############")
print("Virtual Address","Physical Address","Value")
for i in range(250):
    print("0x%08x\t0x%08x\t0x%08x"%(text_virtual_address_begin + 4*i,text_phy_address_begin + 4*i,mem.Data32_port_out(text_phy_address_begin + 4*i)))


### 输出data段
print("############data段###############")
print("Virtual Address","Physical Address","Value")
for i in range(30):
    print("0x%08x\t0x%08x\t0x%08x"%(data_virtual_address_begin + 4*i,data_phy_address_begin + 4*i,mem.Data32_port_out(data_phy_address_begin + 4*i)))

### 输出stack段
print("############stack段###############")
print("Virtual Address","Physical Address","Value")
for i in range(200):
    print("0x%08x\t0x%08x\t0x%08x"%(stack_virtual_address_begin - 4*i,stack_phy_address_begin - 4*i,mem.Data32_port_out(stack_phy_address_begin - 4*i)))


RF.Show_all_register()
# print("PC:",end = "\t")
# PC.output()
